<?php
class SeminarOrgPayment_Controller extends AdminController {
    
    public function __construct() {
        parent::__construct('seminarOrgPayment');
        $this->setDefaultListOrder('begin_date');
    }
    
    function display() {
    	$id = $this->input->get('id');
    	if (! valid::isId($id)) {
    		$this->redirectToList('error.invalidId');
    	}
    	
    	$seminarOrgPayment = $this->dao->getById('seminar_org_payment', $id);
    	if (! $seminarOrgPayment) {
    		$this->msg->error('error-recordNotFound');
    		$this->redirectBack();
    	}
    	
    	$seminar = $this->dao->fetchSeminar($seminarOrgPayment['seminar_id'], $this->getL10nLanguageCode());
    	$organization = $this->dao->getById('organization', $seminarOrgPayment['organization_id']);
    	$seminarOrgPayment['organization_name'] = $organization['name'];
    	
    	$this->viewData['seminar'] = $seminar;
    	$this->viewData['seminarOrgPayment'] = $seminarOrgPayment;
    	$this->viewData['paymentAcceptance'] = $this->dao->getPaymentAcceptance($seminar['id'], $organization['id']);
    	
        $this->renderMySubview('seminarOrgPaymentDisplay');
    }
    
    private function resolveSeminarFromUrlParameter() {
    	$seminarId = $this->input->get('seminar_id');
    	if (! $seminarId) {
    		$seminarId = $this->input->post('seminar_id');
    	}
    	
    	// Basic validation
    	if (! valid::isId($seminarId)) {
    		$this->msg->error('error-invalidId');
    		$this->redirect('/admin/seminar/all');
    	}
    	
    	$seminar = $this->dao->fetchSeminar($seminarId, $this->getL10nLanguageCode());
    	if (! $seminar) {
    		$this->msg->error('error-recordNotFound');
    		$this->redirect('/admin/seminar/all');
    	}
    	return $seminar;
    }
    
    public function listing() {
    	$seminar = $this->resolveSeminarFromUrlParameter();
    	$this->viewData['seminar'] = $seminar;
    	
    	$this->viewData['organizationList'] = $this->dao->queryAll(
    			'SELECT DISTINCT o.* ' .
    			'FROM seminar_org_payment p ' .
    			'JOIN organization o ON p.organization_id = o.id ' .
    			'WHERE p.seminar_id = :seminar_id ' .
    			'ORDER BY o.name',
    			array('seminar_id' => $seminar['id']));
    	foreach ($this->viewData['organizationList'] as &$organization) {
    		$organization['payments'] = $this->dao->queryAll(
	    			'SELECT p.* ' .
	    			'FROM seminar_org_payment p ' .
	    			'WHERE p.seminar_id = :seminar_id ' .
	    			'AND p.organization_id = :org_id ' .
	    			'ORDER BY p.id',
	    			array('seminar_id' => $seminar['id'], 'org_id' => $organization['id']));
    	}
    	
    	$this->renderMySubview('seminarOrgPaymentList');
    }
    
    public function edit() {
    	$id = $this->input->get('id');
    	if ($id) {
    		$seminarOrgPayment = $this->dao->getById('seminar_org_payment', $id);
    		$seminar = $this->dao->fetchSeminar($seminarOrgPayment['seminar_id'], $this->getL10nLanguageCode());
    		$this->viewData['formData'] = $seminarOrgPayment;
    	}
    	else {
    		$seminar = $this->resolveSeminarFromUrlParameter();
    		$this->viewData['formData'] = array('seminar_id' => $seminar['id']);
    	}
    	
    	$organizationId = $_REQUEST['organization_id'];
    	if ($organizationId) {
    		$organization = $this->dao->getById('organization', $organizationId);
    	}
    	
    	$this->viewData['seminar'] = $seminar;
    	
    	$this->loadFormData($seminar, $organization);
    	
    	$this->viewData['formData']['fromAccounts'] = $_REQUEST['fromAccounts'];
    	if ($organization) {
    		$this->viewData['formData']['organization_id'] = $organization['id'];
    	}
    	
    	$this->renderMySubview('seminarOrgPaymentEdit');
    }
    
    public function loadFormData($seminar, $organization = null) {
    	if ($organization) {
    		$orgOptions = array($organization['id'] => $organization['name']);
    	}
    	else {
	    	$orgOptions = $this->dao->queryOptions(
	    			'SELECT o.id, o.name ' .
	    			'FROM organization o ' .
	    			'WHERE o.id IN (SELECT organization_id FROM payment_acceptance pa WHERE pa.seminar_id = :seminar_id AND pa.confirmed_at IS NULL AND (pa.accepts_bank_transfer = :true OR pa.accepts_cash = :true)) ' .
	    			'ORDER BY o.name',
	    			array('seminar_id' => $seminar['id'], 'true' => sql::$TRUE));
    	}
    	$this->viewData['organizationOptions'] = $orgOptions;
    	$this->viewData['fromAccounts'] = $_REQUEST['fromAccounts'];
    	$this->viewData['currencyOptions'] = form::currencyOptions();
    }
    
    public function save() {
    	$seminar = $this->resolveSeminarFromUrlParameter();
    	$this->viewData['seminar'] = $seminar;
    	
    	$formData = $this->postToDbValues();
    	$id = $formData['id'];
    	$this->viewData['formData'] = $formData;
    	
    	// Basic validation
    	$validator = new EntityValidator($formData, 'seminarOrgPayment');
    	$validator->id('organization_id');
    	$validator->code('currency_code');
    	$validator->integer('amount');
    	$validator->dateOrNull('received_on');
    	
    	if ($this->msg->hasErrors()) {
    		$this->loadFormData($seminar);
    		$this->renderMySubview('seminarOrgPaymentEdit');
    		return;
    	}
    	
    	// Database validation
    	$organization = $this->dao->getOrganization($formData['organization_id']);
    	$currency = $this->dao->getByCode('currency', $formData['currency_code']);
    	if (! $organization || ! $currency) {
    		$this->redirectToList('error-invalidId');
    	}
    	
    	if ($formData['payment_identification']) {
	    	$uniqueFields = array ('organization_id', 'seminar_id', 'payment_identification');
	    	if ($this->dao->alreadyExists('seminar_org_payment', $uniqueFields, $formData)) {
	    		$this->loadFormData($seminar);
	    		$this->msg->error('seminarOrgPayment.error-alreadyExists', $formData['payment_identification']);
	    		$this->renderMySubview('seminarOrgPaymentEdit');
	    		return;
	    	}
    	}
    	
    	// Insert or update
        $entity = new SeminarOrgPayment_Model($formData);
        if ($entity->isPersistent()) {
            $this->dao->updateEntity($entity);
            $this->msg->info('seminarOrgPayment.editSuccess', $id, $organization['name']);
        }
        else {
            $id = $this->dao->insertEntity($entity);
            $this->msg->info('seminarOrgPayment.createSuccess', $id, $organization['name']);
        }
    	
        if ($formData['fromAccounts']) {
        	$this->redirect('/admin/seminarAccounts/index');
        }
        else {
    		$this->redirect('/admin/seminarOrgPayment/listing?seminar_id=' . $seminar['id']);
        }
    }
    
    function delete() {
    	$id = $this->input->get('id');
    	if (! valid::isId($id)) {
    		$this->redirectToList('error.invalidId');
    	}
    	
    	$seminarOrgPayment = $this->dao->getById('seminar_org_payment', $id);
    	if (! $seminarOrgPayment) {
    		$this->msg->error('error-recordNotFound');
    		$this->redirectBack();
    	}
    	
    	$seminar = $this->dao->fetchSeminar($seminarOrgPayment['seminar_id'], $this->getL10nLanguageCode());
    	$organization = $this->dao->getById('organization', $seminarOrgPayment['organization_id']);
    
    	// Delete the record, localization values are deleted by cascading.
    	$this->dao->deleteByid('seminar_org_payment', $id);
    
    	$this->msg->info('seminarOrgPayment-deleteSuccess', $id, $organization['name']);
    	$this->redirect('/admin/seminarOrgPayment/listing?seminar_id=' . $seminar['id']);
    }
}
